package com.xdxc.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

public class JwtFilter {

    private static final String SECRET_KEY = "your-secret-key";

    public static void setAuthenticationFromJwt(HttpServletRequest request) {
        String token = request.getHeader("Authorization");

        if (token != null && token.startsWith("Bearer ")) {
            try {
                // 解析 JWT
                Claims claims = Jwts.parser()
                        .setSigningKey(SECRET_KEY)
                        .parseClaimsJws(token.substring(7)) // 去掉 "Bearer " 前缀
                        .getBody();

                // 获取用户名和角色
                String username = claims.getSubject();
                List<String> roles = (List<String>) claims.get("roles");

                // 创建 Authentication 对象
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        username,
                        null,
                        roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList())
                );

                // 设置到 SecurityContext
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } catch (Exception e) {
                // 如果解析失败，可能是无效的 JWT
                SecurityContextHolder.clearContext();
            }
        }
    }
}